import Taro, { Component } from '@tarojs/taro'
import HomePage from './homePage'
import NetWork from '../../util/network'
import './index.scss'
export default class Index extends Component {
  state = {
    Infomation: [],
    template: [],
    navBar: [],
    menuItemTop: '',
    canIUse: false,
    nickName: '',
    loadding: true
  }
  componentDidMount() {
    this.getUserInfoMation()
  }
  async getinitDate() {
    let templateArr = [];
    let { dtos } = await NetWork({ url: '/api/homemenu/loadAppHomeMenuV1', data: {}, method: 'get' });
    dtos.map((v, index) => {
      if (v.menuCode === 'PostInfomartion' || v.menuCode === 'Panorama') {
        dtos.splice(index, 1)
      }
    });
    this.setState({
      navBar: dtos
    });
    dtos.forEach((v, index) => {
      (async (v, index) => {
        let res = await this.AxiosGet(v)
        templateArr[index] = {
          template: v.template,
          title: v.menuName,
          result: {},
          englishName: v.englishName,
          menuCode: v.menuCode, i
        };
        templateArr[index].result = res;
      })(v, index)
    });
    for (var i = 0; i < templateArr.length; i++) {
      if (templateArr[i]) {
        if (templateArr[i].template == 7 && i != 0) {
          var item = templateArr.shift(0);
          templateArr.insert(i, item);
          break;
        }
      }
    }
    this.setState({
      template: templateArr,
    });
    this.GetInfoMation();
  }
  AxiosGet(res) {
    return NetWork({
      url: '/api/homepage/apiLoadAppHomePageDTOV1',
      data: {
        code: res.menuCode,
        keyword: '',
        page: {
          maxResultCount: 0,
          pageNo: 1,
          pageSize: 10,
          skipCount: 0,
        }
      },
      method: 'post'
    });
  }
  async GetInfoMation() {
    let pageNo = this.state.pageNo;
    let infomation = await NetWork({
      url: '/api/postinformation/apiGetPostInformation',
      data: {
        keyword: '',
        nickName: '',
        page: {
          maxResultCount: 0,
          pageNo: pageNo,
          pageSize: 10,
          skipCount: 0,
        },
        topic: '',
      },
      method: 'post'
    });
    this.setState({
      Infomation: infomation.items.items,
    });
  }
  config = {
    navigationBarTitleText: '招商好助手'
  }
  tobegin(res) {
    if (res.detail.userInfo) {
      this.getUserInfoMation()
    }
  }

  onScrollToUpper() { }
  getUserInfoMation() {
    let that = this;
    Taro.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          Taro.getUserInfo({
            success(res) {
              that.setState({
                canIUse: true,
                loadding: false
              })
              that.setState({
                name: res.userInfo.nickName
              })
            },
          })
          Taro.login({
            success(res) {
              if (res.code) {
                that.userLogin(res.code)
              } else {
                console.log('登录失败！' + res.errMsg)
              }
            }
          })
        } else {
          that.setState({
            canIUse: false,
            loadding: false
          })
        }
      }
    })
  }
  async userLogin(code) {
    let result = await NetWork({
      url: "/api/getWeChatOpenId",
      data: {
        jsCode: code
      },
      method: 'get'
    })
    let res = await NetWork({
      url: "/api/thirdplatformlogin",
      data: {
        wechatopenid: result
      },
      method: "post"
    })

    if (!res) {
      Taro.redirectTo({
        url: '/pages/register/index?thirdPlatformInfoDTO=' + result
      })
    } else {
      Taro.setStorage({
        key: "Authorization",
        data: res
      })

      this.getinitDate();
    }
  }
  jumpTo(topArr, params) {
    let result = topArr.some(v => v.menuCode == params) ? topArr.filter(v => v.menuCode == params)[0].height : ''
    Taro.pageScrollTo({
      scrollTop: result,
      duration: 300
    })
  }
  changeState(navBar) {
    let arr = []
    let height = 0
    if (!navBar.length) {
      return false
    }
    navBar.map(items => {
      switch (items.template) {
        case 1:
          arr.push({ menuCode: items.menuCode, height })
          height += 498
          break;
        case 2:
          arr.push({ menuCode: items.menuCode, height })
          height += 360
          break;
        case 3:
          arr.push({ menuCode: items.menuCode, height })
          height += 239
          break;
        case 4:
          arr.push({ menuCode: items.menuCode, height })
          break;
        case 5:
          arr.push({ menuCode: items.menuCode, height })
          height += (216 * items.pageSize + 65)
          break;
        case 7:
          arr.push({ menuCode: items.menuCode, height })
          height += 404
          break;
      }
    })
    return arr
  }
  render() {
    let topArr = this.changeState(JSON.parse(JSON.stringify(this.state.navBar)))
    return (
      this.state.loadding ? '' :
        !this.state.canIUse ? <View className='warpLogin'>
          <Button open-type="getUserInfo" onGetUserInfo={this.tobegin} type='primary'>登录</Button>
        </View> :
          this.state.template.map(items => (
            <HomePage items={items}
              navBar={this.state.navBar}
              key={items.menuCode}
              jumpTo={this.jumpTo.bind(this, topArr)}
              Infomation={this.state.Infomation} />
          ))

    )
  }
} 
